from django.shortcuts import redirect,render,reverse,HttpResponse
from .models import Course,Category
from user.models import User
from django.http import StreamingHttpResponse
import os
# Create your views here.
def index_handler(request):
    #定义 context对象，传递给模板
    context=request.context
    #得到所有的课程种类对象
    category_s=Category.objects.all()
    #定义课程内容列表
    course_data_s=[]
    #对得到的所有课程种类进行遍历
    for category in category_s:
        #course_data_s列表封装数据如下
        course_data_s.append(
            {
                # 课程的种类名称
                'category': category.name,
                # 课程种类中包含的所有课程对象
                'course_s': category.courses_set.all()
            }
        )
    #把course_data_s添加到context字典中
    context['course_data_s'] =course_data_s
    #渲染模板
    return render(request,"index.html",context)


def course_handler(request,courseid):
    print("courseid",courseid)
    context = request.context
    try:
        course = Course.objects.get(id=courseid)
        session_user = request.session.get("session_user",None)
        if session_user:
            context["view_perssion"] = User.objects.filter(id=session_user.get("id"),userBuyer_set__id = course.id).exists()
        context["course"] = course
        return render(request,'course.html',context)
    except:
        return HttpResponse(status=404)




def video_handler(request,courseid):
    context=request.context
    try:
        course = Course.objects.get(id=courseid)
        session_user = request.session.get("session_user", None)
        boolean_buyed= User.objects.filter(id=session_user.get('id'),userBuyer_set__id=courseid).exists()
        if boolean_buyed:
            context['course'] =course
            return render(request,'video.html',context)
        else:
            return redirect(reverse('course_course',args=(course.id,)))
    except:
        return HttpResponse(status=404)



def videoStream_handler(request,courseid):
    # 根据path来读取视频文件
    def read_video(path):
        with open(path,'rb') as f:
                while True:
                    data =f.read(1024 * 10)
                    if data:
                        yield data
                    else:
                        break
    context = request.context
    try:
        course = Course.objects.get(id=courseid)
        session_user = request.session.get("session_user", None)
        boolean_buyed = User.objects.filter(id=session_user.get('id'), userBuyer_set__id=courseid).exists()
        if boolean_buyed:
            context['course'] = course
            response=StreamingHttpResponse(read_video(course.fileName.__str__()),status=206)
            # 每次返回的最大字节数
            bytes_max = 1024 * 1024 * 2  # 2M
            # 响应的Content-Range
            # 0：表示起始字节
            # 第一个%s，每次返回的最大字节数
            # 第二个%s，文件的总大小
            response['Content-Range'] = 'bytes 0-%s/%s' % (bytes_max, os.path.getsize(course.fileName.__str__()))
            # 返回响应
            return response
        else:
            return redirect(reverse('course_course', args=(course.id,)))
    except:
        return HttpResponse(status=404)